<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 文件相关Controller v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\controller;


use addons\common\task\AddonsCronTask;
use app\core\model\CronTask;
use think\Loader;

class TaskController extends CoreBaseController {

    public function runCron() {
        //TODO 安全性检查

        //获取cronTask
        $cronTaskId = input("post.cronTaskId");
        $cronTask = CronTask::getById($cronTaskId);
        if(empty($cronTask)) {
            return json([
                "code" => AddonsCronTask::CODE_NOT_FOUND,
                "msg" => "未找到指定任务"
            ]);
        }

        //设置脚本最大执行时间
        $timeout = fetch($cronTask, 'timeout', 0);
        set_time_limit($timeout);

        //引入相关namespace
        Loader::addNamespace("addons\\" . $cronTask['module'],
            ROOT_PATH . "addons" . DS . $cronTask['module']);
        Loader::addNamespace("addons\\common",
            ROOT_PATH . "addons" . DS . "common");
        //反射生成任务类
        $packageName = "addons\\" . $cronTask['module'] . "\\task\\";
        $classFullName = $packageName . $cronTask['name'];
        Loader::import($classFullName, ROOT_PATH, EXT);
        $taskClass = new $classFullName($cronTask);
        //执行任务
        CronTask::addLog($cronTask, "开始执行任务：" . json_encode($cronTask));
        $ret = $taskClass->run();
        CronTask::addLog($cronTask, "开始执行结束：" . json_encode($ret));

        return json($ret);
    }
}
